package cn.ixinjiu.libraryMangement.utils;

import java.sql.*;

/**
 * Created by XinChen on 2023-05-07
 *
 * @TODO JDBC连接数据库工具类
 */
public class JDBCUtil {
    private static Connection connection = null;
    private static PreparedStatement preparedStatement = null;
    private static ResultSet resultSet = null;

    // 本地数据库url路径
    private static String url = "jdbc:mysql://127.0.0.1:3306/library?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
    // 本地数据库用户名
    private static String user = "root";
    // 本地数据库密码，根据本地情况作出修改
    private static String password = "123456";

    // 静态带代码块：在类加载的时候只执行这一次
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 获取连接
    public static Connection getConnection() {
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 查询通用方法
     *
     * @param sql     调用方法时传入的SQL语句
     * @param objects 调用方法时传入数组，数组元素用于SQL语句占位符填充值
     * @return java.sql.ResultSet
     */
    public static ResultSet query(String sql, Object[] objects) throws SQLException {
        getConnection(); // 获取连接
        preparedStatement = connection.prepareStatement(sql);
        if (objects != null) {
            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject(i + 1, objects[i]);
            }
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }

    // 通用增删改
    public static int update(String sql, Object[] objects) {
        getConnection();
        int count = 0;
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (objects != null) {
                for (int i = 0; i < objects.length; i++) {
                    preparedStatement.setObject(i + 1, objects[i]);
                }
            }
            count = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return count;
    }

    // 关闭资源
    public static void close() {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
